﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hopscotch.Common;

namespace Hopscotch.Presentation.Configuration
{
    public class EnvironmentsConfigurationSection : ConfigurationSection, IEnvironmentsConfiguration
    {
        public const string SectionName = "environments";

        public IEnumerable<IEnvironmentConfiguration> Environments
        {
            get
            {
                return EnvironmentElementCollection.OfType<IEnvironmentConfiguration>();
            }
        }

        [ConfigurationProperty("", IsDefaultCollection = true, IsKey = false)]
        public EnvironmentConfigurationElementCollection EnvironmentElementCollection
        {
            get { return (EnvironmentConfigurationElementCollection)base[""]; }
            set { base[""] = value; }
        }
    }

    [ConfigurationCollection(typeof(EnvironmentConfigurationElement), AddItemName = "environment", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class EnvironmentConfigurationElementCollection : ConfigurationElementCollection
    {
        public EnvironmentConfigurationElement this[int index]
        {
            get { return (EnvironmentConfigurationElement)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public void Add(EnvironmentConfigurationElement serviceConfig)
        {
            BaseAdd(serviceConfig);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new EnvironmentConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((EnvironmentConfigurationElement)element).EnvironmentId;
        }

        public void Remove(EnvironmentConfigurationElement serviceConfig)
        {
            BaseRemove(serviceConfig.EnvironmentId);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(String name)
        {
            BaseRemove(name);
        }
    }
}
